package com.shenghua.utils.sysutil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

/**
 * Created by Administrator on 2019/4/29.
 */
public class MapUtils {

    /**
     * 检查Map是否存在空值
     * @param paramMap
     * @return
     */
    public static boolean checkMapExistNull(Map<String, Object> paramMap) {
        JSONObject requestParams = JSONObject.parseObject(JSON.toJSONString(paramMap));
        Set<Object> set = new HashSet<>();
        for (Map.Entry<String, Object> m : paramMap.entrySet()) {
            set.add(m.getKey());
        }
        if (requestParams == null) {
            return false;
        }
        if (set == null || set.size() == 0) {
            return true;
        }
        Set<?> jsonSet = requestParams.keySet();
        if (jsonSet.containsAll(set))
            return true;
        else
            return false;
    }

    /**
     *  map 转对象
     * @param mp
     * @param beanCls
     * @param <T>
     * @param <K>
     * @param <V>
     * @return
     *  T value = (T) parser.parseObject(clazz);
     */
    public static <T, K, V> T mapToObject(Map<K, V> mp, Class<T> beanCls) {
        T t = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(beanCls);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            t = beanCls.newInstance();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                if (key.equals("trade_balance")) {
                    System.out.println(key);
                }
                if (mp.containsKey(key)) {
                    Object value = mp.get(key);
                    System.out.println(key + "----" + value);
                    Method setter = property.getWriteMethod();
                    try {
                        setter.invoke(t, value);
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 转换对象为map
     *
     * @param object
     * @param ignore
     * @return
     */
    public static Map<String, String> objectToMap(Object object, String... ignore) {
        Map<String, String> tempMap = new LinkedHashMap<>();
        for (Field f : getAllFields(object.getClass())) {
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            boolean ig = false;
            if (ignore != null && ignore.length > 0) {
                for (String i : ignore) {
                    if (i.equals(f.getName())) {
                        ig = true;
                        break;
                    }
                }
            }
            if (ig) {
                continue;
            } else {
                Object o = null;
                try {
                    o = f.get(object);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (!f.getName().equals("serialVersionUID") && !f.getName().equals("FAIL")
                        && !f.getName().equals("OKMSG") && !f.getName().equals("SUCCESS")
                        && !f.getName().equals("hmac"))
                    tempMap.put(f.getName(), o == null ? "" : o.toString());
            }
        }
        return tempMap;
    }

    /**
     * 转换对象为map
     *
     * @param object
     * @param ignore
     * @return
     */
    public static Map<String, Object> objToMap(Object object, String... ignore) {
        Map<String, Object> tempMap = new LinkedHashMap<String, Object>();
        for (Field f : getAllFields(object.getClass())) {
            if (!f.isAccessible()) {
                f.setAccessible(true);
            }
            boolean ig = false;
            if (ignore != null && ignore.length > 0) {
                for (String i : ignore) {
                    if (i.equals(f.getName())) {
                        ig = true;
                        break;
                    }
                }
            }
            if (ig) {
                continue;
            } else {
                Object o = null;
                try {
                    o = f.get(object);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (!f.getName().equals("serialVersionUID") && !f.getName().equals("FAIL")
                        && !f.getName().equals("OKMSG") && !f.getName().equals("SUCCESS")
                        && !f.getName().equals("hmac"))
                    if (null != o) {
                        tempMap.put(f.getName(), o == null ? "" : o.toString());
                    }
            }
        }
        return tempMap;
    }

    /**
     * String 转 Map<String, String>
     * @param param
     * @return
     */
    public static Map<String, String> strToMap(String param) {
        Map<String, String> map = new TreeMap<>();
        if(param.startsWith("{") && param.endsWith("}")) {
            param = param.substring(1,param.length()-1);
        }
        String[] split = param.split(",");
        for (String string : split) {
            String[] split2 = string.split("=");
            System.out.println(split2[0].trim() + " : " + split2[1].trim());
            map.put(split2[0].trim(), split2[1].trim());
        }
        return map;
    }

    public static Map<String, Object> urlToMap(String result){
        String[] split = result.split("&");
        Map<String,Object> map = new HashMap<>();
        for (String str : split) {
            String[] split2 = str.split("=");
            map.put(split2[0], split2[1]);
        }
        System.out.println("url 转Map ：" + map);
        return map;
    }

    public static Map<String, Object> JSONObjectToMap(JSONObject object) {
        Map<String,Object> map = new HashMap<>();
        Set<String> sets = object.keySet();
        for (String str: sets) {
            System.out.println(str + " : " + object.get(str).toString());
            map.put(str, object.get(str));
        }
        return map;
    }

    public static Map<String, Object> JSONStringToMap(String string) {
        JSONObject object = JSON.parseObject(string);
        return JSONObjectToMap(object);
    }
    /**
     * 获取所有Fields,包含父类field
     *
     * @param clazz
     * @return
     */
    private static List<Field> getAllFields(Class<?> clazz) {
        if (!clazz.equals(Object.class)) {
            List<Field> fields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()));
            List<Field> fields2 = getAllFields(clazz.getSuperclass());
            if (fields2 != null) {
                fields.addAll(fields2);
            }
            return fields;
        } else {
            return null;
        }
    }

    public static boolean isNotEmpty(Map map) {
        if(null != map && map.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isEmpty(Map map) {
        return !isNotEmpty(map);
    }

    public static void main(String[] args){
        String string = "{\"addr\":\"福建省泉州市宝洲路万达A座3806\",\"amount\":\"585796\",\"areaCode\":\"150000\",\"areaName\":\"内蒙古自治区\",\"bankCardNumber\":\"6217000410008650702\",\"city\":\"150100\",\"cityName\":\"呼和浩特市\",\"fullName\":\"徐会玲\",\"high\":0,\"iP\":\"139.196.87.37\",\"idCardEffectiveEndTime\":\"2030-03-02\",\"legalIdCard\":\"220221197809090529\",\"legalPerson\":\"徐会玲\",\"level\":\"C1\",\"merchantInto\":{\"aptitudeNo\":\"1319051708363591\",\"created\":1558053369000,\"deskey\":\"564bccfe319146f790bd207a62171e63\",\"fullName\":\"徐会玲\",\"id\":301847,\"intoStatus\":\"yes\",\"merchantName\":\"徐会玲\",\"merchantNo\":\"M1553231573268\",\"organizationNo\":\"00000000\",\"payPassagewayNo\":\"P20190319194637\",\"rate\":\"0.0051\",\"reserved1\":\"200\",\"reserved2\":\"6217000410008650702\",\"reserved5\":\"1319051708363591\"},\"merchantName\":\"徐会玲\",\"merchantNo\":\"M1553231573268\",\"openingBankLineNumber\":\"105191066767\",\"orderNo\":\"W20190517083895675\",\"payType\":\"preferredQuickAndIntegral\",\"payTypeClass\":{\"created\":1526977192000,\"creater\":\"管理员\",\"del\":\"yes\",\"id\":173,\"initialFee\":0,\"name\":\"银联快\n" +
                "捷(优选有积分)\",\"organizationNo\":\"00000000\",\"payMode\":\"quick\",\"payType\":\"preferredQuickAndIntegral\",\"poundage\":200,\"rank\":\"C1\",\"rate\":0.0051,\"scanType\":\"quickA\",\"settlementType\":\"t0\",\"status\":\"enable\",\"updated\":1555469302000},\"phone\":\"15548812626\",\"poundage\":0,\"province\":\"150000\",\"provinceName\":\"内蒙古自治区\",\"rate\":0,\"realAuditStatus\":\"nouploaded\",\"settlementCard\":{\"auditStatus\":\"passMer\",\"auditd\":\"张华瑜\",\"bankNo\":8,\"bankNum\":\"0105\",\"behindImg\":\"/upload/F488E780DBB4C094A78FFF88A73DD468.jpg\",\"behindStatus\":\"passMer\",\"branchName\":\"CCB\",\"cardType\":\"settlement\",\"cardholder\":\"徐会玲\",\"cityCode\":\"150100\",\"created\":1553308847000,\"defaultStatus\":\"defaults\",\"frontImg\":\"/upload/F0016F6A3502E8BB51C53445DC7A4CEF.jpg\",\"frontStatus\":\"passMer\",\"id\":35534,\"idCard\":\"220221197809090529\",\"merchantNo\":\"M1553231573268\",\"openingBank\":\"中国建设银行\",\"openingBankLineNumber\":\"105191066767\",\"openingBankName\":\"中国建设银行股份有限公司呼和浩特锡林南路万锦支行\",\"openingBankPhone\":\"15548812626\",\"organizationNo\":\"00000000\",\"phone\":\"15548812626\",\"provinceCode\":\"150000\",\"settlementNo\":\"6217000410008650702\",\"status\":\"normal\",\"updated\":1553310281000},\"taccountId\":\"M1553231573268\",\"terminalType\":\"t0\",\"tradeMoney\":\"589000\",\"userOrder\":{\"agentCost\":0,\"channelOrderNo\":\"O20190517083881388\",\"city\":\"150100\",\"clientIp\":\"139.196.87.37\",\"created\":1558053481000,\"fee\":3004,\"id\":2003945,\"incomeAmount\":585796,\"ismerchant\":\"no\",\"mchId\":\"1\",\"merchantLevel\":\"C1\",\"merchantName\":\"徐会玲_\",\"merchantNo\":\"M1553231573268\",\"obtainMoney\":335,\"orderNo\":\"O20190517083881388\",\"orderReqTime\":1558053481000,\"orderResDate\":1558053495670,\"organizationNo\":\"00000000\",\"passagewayType\":\"quick\",\"payCardName\":\"中国光大银行\",\"payCardNo\":\"6226850000601057\",\"payCompleteTime\":1558053494000,\"payPassagewayCost\":2524,\"payPassagewayName\":\"畅捷全银行商旅\",\"payPassagewayNo\":\"P20190319194637\",\"payPassagewayRate\":0.0042,\"payStatus\":\"paymentSuccess\",\"payType\":\"preferredQuickAndIntegral\",\"phone\":\"15548812626\",\"poundage\":200,\"profit\":345,\"province\":\"150000\",\"rate\":0.0051,\"refundStatus\":\"unrefund\",\"remark\":\"dc4d7402c3be521b\",\"reqStateDesc\":\"SUCCESS\",\"reqStatus\":\"200\",\"riskState\":\"noFreeze\",\"scanType\":\"quickA\",\"serverIp\":\"172.19.33.182\",\"settlementStatus\":\"settled\",\"settlementTime\":1558060695000,\"settlementType\":\"t0\",\"tradeMoney\":589000},\"wide\":0}";

        JSONStringToMap(string);
    }

}
